<template>
  <div class="container">
    <div class="left">
      <div class="left-title">指标列表</div>
      <div class="left-operate-box">
        <a-select v-model="currentIndexConfig" :options="indexConfigList" placeholder="请选择配置" @change="currentIndexConfigChange" />
        <a-icon type="reload" :spin="loading" class="icon" title="刷新" @click="reLoadIndexConfigList" />
        <a-input v-model="searchValue" placeholder="请输入指标名称">
          <a-icon slot="suffix" type="search" />
        </a-input>
      </div>
      <div class="table-list" :style="{ display: currentIndexList.length === 0 ? 'flex' : '' }">
        <a-empty v-if="currentIndexList.length === 0" :image="emptyCustomImage" description="暂无指标" />
        <template v-else v-for="(item, index) in currentIndexList">
          <div
            v-if="item.name.indexOf(searchValue) > -1"
            :key="index"
            :class="['table-item']"
            :title="item.name"
            draggable="true"
            @dragstart="event => dragstart(event, item)"
            @dragend="event => dragend(event, item)"
            >
            <p>{{ item.name }}</p>
          </div>
        </template>
      </div>
    </div>
    <div class="middle">
      <div class="operate-box">
        <a-select
          v-model="currentCalculateFunction"
          @change="currentCalculateFunctionChange"
          placeholder="请选择计算公式"
        >
          <a-select-option
            v-for="(item,index) in calculateFunctionList"
            :key="'calculateFunction' + index"
            :value="item.id">
           {{ item.name }}
          </a-select-option>
        </a-select>
        <a-button @click="test">试计算</a-button>
      </div>
      <div ref="calculateFunctionPanel" class="select-box" :style="{ justifyContent: currentIndexList.length !== 0 && !calculateFunctionContainerHorizontalAlignIsCenter ?  'flex-start' : 'center' }">
        <a-empty v-if="currentCalculateFunction === undefined" :image="emptyCustomImage" description="请选择指标计算函数" />
        <div class="select-calculate-box" v-else>
          <template>
            <div v-for="(formula, index) in formulaStrs" :key="'formula' + index">
              <div class="symbol-container" v-if="!isValid(formula.name)">{{ formula.name }}</div>
              <div @dragover="event => dragover(event, index)" v-else class="variable-container" :class="selectedIndexOfIdList.length === 0 ? 'variable-container-empty' : 'variable-container-full'" :style="{ display: selectedIndexOfIdList.length === 0 ? 'flex' : '', position:'relative' }">
                <a-empty v-if="formula.indexName == null || formula.indexName == ''" :image="emptyCustomImage" description="请选择计算指标" />
                <template v-else>
                  <a-button title="取消选择" @click="indexUnselect(formula.name, index)" type="text" icon="close" style="position:absolute;right:-10px;top:0" />
                  <div class="variable-details-container">
                    <span>指标名称：{{ formula.indexName }}</span>
                    <!-- <span>时间维度：{{ currentCalculateFunctionCode === 'yearOnYear' || currentCalculateFunctionCode === 'yearOnYearGrowthRate' ? '同期' : '上期' }}</span> -->
                  </div>
                  <a-button title="设置" @click="installIndex(formula, index)" type="primary" style="position:absolute;right:-10px;bottom:0" >设置</a-button>
                </template>
              </div>
            </div>
          </template>
        </div>
      </div>
      <div class="result-title">试计算结果</div>
      <div class="result-box" :style="{ display: testResult.length === 0 ? 'flex' : '' }">
        <a-table
        v-if="testResult.length > 0"
        bordered
        class="j-table-force-nowrap"
        style="background: #ffffff;"
        rowKey="testId"
        :pagination="false"
        :columns="resultTableColumns"
        :dataSource="testResult" />
        <a-empty v-else :image="emptyCustomImage" />
      </div>
    </div>
    <div class="right">
      <div class="right-title">维度信息</div>
      <div class="right-box-1" :style="{ display: selectedDimensionList.length === 0 ? 'flex' : '' }">
        <a-empty v-if="selectedDimensionList.length === 0" :image="emptyCustomImage" description="请选择计算指标" />
        <a-checkbox-group v-else v-model="checkedDimension" style="width: 100%" @change="changeDimension">
          <a-row>
            <a-col :span="24" v-for="(item, index) in selectedDimensionList" :key="'checkedDimension' + index">
              <a-checkbox :value="item.id">{{ item.name }}</a-checkbox>
            </a-col>
          </a-row>
        </a-checkbox-group>
      </div>
      <div class="right-title">指标定义</div>
      <div class="right-box-2">
        <a-form :form="form">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="指标名称">
            <a-input v-decorator="['indexName', { rules: [{ required: true, message: '请输入指标名称', pattern: '[^ \x22]+' }, { pattern: /^[a-zA-Z]{1}(?!_)[a-zA-Z0-9_\\$]+$/, message: '命名规则:只能由字母、数字、下划线、$符号组成;必须以字母开头;不能以单个字母加下滑线开头' }] } ]" placeholder="请输入指标名称" />
          </a-form-item>
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="备注">
            <a-textarea v-decorator="['remark', { 'initialValue': '' }]" allowClear autoSize placeholder="请输入备注" />
          </a-form-item>
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="数据类型">
            <j-dict-select-tag v-decorator="['dataType', { rules: [{ required: true, message: '请选择数据类型' }]}]" dictCode="column_data_type" placeholder="请选择数据类型" :trigger-change="true" />
          </a-form-item>
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="长度">
            <a-input-number v-decorator="['columnLength', { 'initialValue': 20 }]" :min="0" :precision="0" style="width: 100%;" />
          </a-form-item>
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="小数精度">
            <a-input-number v-decorator="['scale', { 'initialValue': 0 }]" :min="0" :precision="0" style="width: 100%;" />
          </a-form-item>
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="统计单位">
            <a-input v-decorator="['unit', { 'initialValue': '' }]" allowClear placeholder="请输入统计单位" />
          </a-form-item>
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="是否率值">
            <a-radio-group v-decorator="['isPercent', { 'initialValue': 0 }]" @change="handleIsPercentChange">
              <a-radio :value="1">是</a-radio>
              <a-radio :value="0">否</a-radio>
            </a-radio-group>
          </a-form-item>
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="汇聚方式" v-show="false">
            <!-- , { rules: [{ required: form.getFieldValue('isPercent') === 0, message: '请选择汇聚方式' }]} -->
            <j-dict-select-tag v-decorator="['groupType']" dictCode="index_group_type" placeholder="请选择汇聚方式" :trigger-change="true" :disabled="form.getFieldValue('isPercent') === 1" />
          </a-form-item>
        </a-form>
      </div>
    </div>

    <!-- 指标设置页面 -->
    <a-modal v-model="indexInstallVisible" width="1000px" title="指标设置" @ok="handleInstall"  @cancel="handleCancelInstall">
      <a-row>
        <a-col :span="4"><div class="install-label">指标参数：</div></a-col>
        <a-col :span="18"><a-input placeholder="请输入名称" disabled v-model="installIndexObj.name"/></a-col>

        <a-col :span="24"><div style="width:100%;height: 20px" /></a-col>
        <a-col :span="4"><div class="install-label">指标名称：</div></a-col>
        <a-col :span="18"><a-input placeholder="请输入名称" disabled v-model="installIndexObj.indexName"/></a-col>

        <a-col :span="24"><div style="width:100%;height: 20px" /></a-col>
        <a-col :span="4"><div class="install-label">IF条件：</div></a-col>
        <a-col :span="18">
          <a-row>
            <a-col :span="24">
              <a-select v-model="installIndexObj.judgingAction"  style="width: 100%;">
                <a-select-option key="And"> And(所有条件都要求匹配) </a-select-option>
                <a-select-option key="Or"> Or(条件中的任意一个匹配) </a-select-option>
              </a-select>
            </a-col>
            <div v-for="(item, index) in installIndexObj.judgingConditions" :key="'judgingCondition' + index">
              <a-col :span="24"><div style="width:100%;height: 20px" /></a-col>
              <a-col :span="10">
                <a-select
                  v-model="item.judgmentSymbol"
                  placeholder="请选择过滤条件"
                  style="width: 100%;">
                  <a-select-option v-for="tag in optionRuleArray" :key="tag.id">{{ tag.name }}</a-select-option>
                </a-select>
              </a-col>
              <a-col :span="10">
                <a-input
                  allowClear
                  placeholder="请输入字段值"
                  style="width: 100%;"
                  v-model="item.judgmentValue"
                />
              </a-col>
              <a-col :span="2">
                <a-button style="width: 40px; margin-left: 15px;" @click="handleAddItem(item)">+</a-button>
              </a-col>
              <a-col :span="2">
                <a-button style="width: 40px; margin-left: 5px;" :disabled="installIndexObj.judgingConditions.length == 1" @click="handleDeleteItem(index)">-</a-button>
              </a-col>
            </div>
          </a-row>
        </a-col>

        <a-col :span="24"><div style="width:100%;height: 20px" /></a-col>
        <a-col :span="4"><div class="install-label">IF条件通过时：</div></a-col>
        <a-col :span="18">
          <a-row>
            <a-col :span="10">
              <div class="install-label">
                <a-input disabled v-model="installIndexObj.indexName"/>
              </div>
            </a-col>
            <a-col :span="4">
              <a-select
                  v-model="installIndexObj.trueValueRule"
                  placeholder="请选择过滤条件"
                  style="width: 100%;">
                  <a-select-option v-for="tag in trueValueRules" :key="tag.id">{{ tag.name }}</a-select-option>
                </a-select>
            </a-col>
            <a-col :span="10">
              <a-input-number placeholder="请输入IF条件通过时值" v-model="installIndexObj.trueValue" style="width: 100%;" />
            </a-col>
          </a-row>
        </a-col>

        <a-col :span="24"><div style="width:100%;height: 20px" /></a-col>
        <a-col :span="4"><div class="install-label">IF条件不通过时：</div></a-col>
        <a-col :span="18">
          <a-row>
            <a-col :span="10">
              <div class="install-label">
                <a-input disabled v-model="installIndexObj.indexName"/>
              </div>
            </a-col>
            <a-col :span="4">
              <a-select
                  v-model="installIndexObj.falseValueRule"
                  placeholder="请选择过滤条件"
                  style="width: 100%;">
                  <a-select-option v-for="tag in trueValueRules" :key="tag.id">{{ tag.name }}</a-select-option>
                </a-select>
            </a-col>
            <a-col :span="10">
              <a-input-number placeholder="请输入IF条件不通过时值" v-model="installIndexObj.falseValue" style="width: 100%;" />
            </a-col>
          </a-row>
        </a-col>

        <a-col :span="24"><div style="width:100%;height: 20px" /></a-col>
        <a-col :span="4"><div class="install-label">IFNULL：</div></a-col>
        <a-col :span="18"><a-input placeholder="请输入为空时默认值" v-model="installIndexObj.emptyDefaultValue"/></a-col>

        <a-col :span="24"><div style="width:100%;height: 20px" /></a-col>
        <a-col :span="4"><div class="install-label">汇聚方式：</div></a-col>
        <a-col :span="18">
          <j-dict-select-tag style="width:100%" v-model="installIndexObj.aggregateType" dictCode="index_group_type" placeholder="请选择汇聚方式" />
        </a-col>

        <a-col :span="24"><div style="width:100%;height: 20px" /></a-col>
        <a-col :span="4"><div class="install-label">非关联维度过滤：</div></a-col>
        <a-col :span="18">
          <a-select mode="multiple" style="width:100%" v-model="installIndexObj.fieldName" placeholder="请选择非关联维度" @change="changeFieldName">
            <a-select-option :value="item.id" :key="'feiguanlianweidu' + item.id" v-for="item in installIndexObj.dimensionList">{{ item.name }}</a-select-option>
          </a-select>
        </a-col>
        <div v-if="installIndexObj.feiguanlianweidu">
          <div v-for="(item, index) in installIndexObj.feiguanlianweidu" :key="'feiguanlianweidu' + index">
            <a-col :span="24"><div style="width:100%;height: 20px" /></a-col>
            <a-col :span="4"><div class="install-label">{{item.label}}：</div></a-col>
            <a-col :span="18">
              <a-select mode="multiple" style="width:100%" v-model="item.value" placeholder="请选择非关联维度">
                <a-select-option :value="item1.value" :key="'feiguanlianweidu' + item1.value" v-for="item1 in item.fields">{{ item1.text }}</a-select-option>
              </a-select>
            </a-col>
          </div>
        </div>
      </a-row>
    </a-modal>
  </div>
</template>

<script>
import pick from 'lodash.pick'
import elementResizeDetector from 'element-resize-detector'
import { Empty } from 'ant-design-vue'
import { getAction, postAction } from '@/api/manage'

export default {
  name: 'CreateIndexByIndex',
  props: {
    baseInfo: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data() {
    return {
      trueValueRules: [
        { id: '=', name: '=' },
        { id: '+', name: '+' },
        { id: '-', name: '-' },
        { id: '*', name: '*' },
        { id: '/', name: '/' }
      ],
      // 判断符号
      optionRuleArray: [
        { id: 'eq', name: '等于' },
        { id: 'like', name: '包含' },
        { id: 'right_like', name: '以..开始' },
        { id: 'left_like', name: '以..结尾' },
        { id: 'in', name: '在...中' },
        { id: 'ne', name: '不等于' },
        { id: 'gt', name: '大于' },
        { id: 'ge', name: '大于等于' },
        { id: 'lt', name: '小于' },
        { id: 'le', name: '小于等于' }
      ],
      checkedDimension: null,
      selectedDimensionList: [],
      installIndexObj: {
        judgingAction: null,
        emptyDefaultValue: null,
        trueValue: null,
        trueValueRule: '=',
        falseValue: null,
        falseValueRule: '=',
        judgingConditions: [
          {
            judgmentSymbol: null,
            judgmentValue: null
          }
        ],
        feiguanlianweidu: [],
        name: null,
        indexName: null,
        indexId: null,
        dimensionList: [],
        fieldName: []
      },
      indexInstallVisible: false,
      selectedIndexObj: null,
      selectedFormulaStrIndex: null,
      operators: ['+', '-', '*', '/', '(', ')', '%', '^', '!', '|'],
      formulaStr: null,
      formulaStrs: [], // 分解后的公式
      emptyCustomImage: Empty.PRESENTED_IMAGE_SIMPLE,
      loading: false,
      currentIndexConfig: undefined, // 当前选中的指标配置项参数
      indexConfigList: [], // 指标配置项数据数组参数
      searchValue: '', // 指标模糊搜索参数
      currentIndexList: [], // 当前选中指标配置对应的指标列表数组参数
      currentDimensionList: [], // 当前选中指标配置对应的维度列表数组参数
      calculateFunctionContainerHorizontalAlignIsCenter: true,
      currentCalculateFunction: undefined, // 当前选中的指标计算函数参数
      currentCalculateFunctionCode: '', // 当前选中的指标计算函数对应代号参数
      currentCalculateFunctionMatchingDimension: [], // 当前选中的指标计算函数需要匹配的维度数组参数
      calculateFunctionList: [], // 指标计算函数数组参数
      indexDefinitionModel: {}, // 指标定义数据回填对象参数
      selectedIndexOfIdList: [], // 存放选取的指标对应的id的数组参数
      selectedIndexList: [], // 存放选取的指标对应数据的数组参数
      form: this.$form.createForm(this),
      labelCol: { span: 10 },
      wrapperCol: { span: 14 },
      testCompleteFlag: false, // 试计通过标识参数，默认为false
      resultTableColumns: [],
      resultTableIndexColumn: {
        title: '#',
        dataIndex: '',
        key: 'rowIndex',
        width: 60,
        align: 'center',
        customRender: function(t, r, index) {
          return parseInt(index) + 1
        }
      },
      testResult: [],
      url: {
        indexConfigList: '/index/config/listAllConfig',
        calculateFunctionList: '/index/compute/scSituationFormula/list',
        indexDetails: '/index/scSituationIndexInfo/queryById',
        test: '/index/config/testRunning',
        summit: '/index/config/saveIndex'
      }
    }
  },
  computed: {
    currentDefaultDimension: function() {
      const temp = this.currentDimensionList.filter(item => { return item.disabled === true })
      return temp[0].name
    }
  },
  mounted() {
    this.initIndexConfigList()
    this.initCalculateFunctionList()
    this.initCalculateFunctionContainerSizeListener()
  },
  methods: {
    handleAddItem() {
      this.installIndexObj.judgingConditions.push({
        judgmentSymbol: null,
        judgmentValue: null
      })
    },
    handleDeleteItem(index) {
      this.installIndexObj.judgingConditions.splice(index, 1)
    },
    changeDimension() {
      console.log(this.checkedDimension)
    },
    changeFieldName() {
      if (this.installIndexObj.fieldName != null && this.installIndexObj.fieldName != '') {
        var fieldNames = (this.installIndexObj.fieldName + '').split(',')
        if (!this.installIndexObj.feiguanlianweidu) {
          this.installIndexObj.feiguanlianweidu = []
        }

        fieldNames.forEach(item => {
          console.log(item)
          var fieldObj = this.installIndexObj.dimensionList.find(item1 => item1.id == item)
          if (this.installIndexObj.feiguanlianweidu.findIndex(item1 => item1.fieldName == item) == -1) {
            getAction('/dimension/scSituationDimensionType/getDimensionDict', { dimensionTypeId: fieldObj.dimensionType }).then(res => {
              if (res.success) {
                this.installIndexObj.feiguanlianweidu.push({
                  fieldName: item,
                  value: [],
                  tableColumn: fieldObj.tableColumn,
                  label: fieldObj.name,
                  fields: res.result
                })

                console.log(this.installIndexObj.feiguanlianweidu)
              }
            })
          }
        })

        this.installIndexObj.feiguanlianweidu.forEach((item, index) => {
          if (fieldNames.findIndex(item1 => item.fieldName == item1) == -1) {
            this.installIndexObj.feiguanlianweidu.splice(index, 1)
          }
        })
      } else {
        this.installIndexObj.feiguanlianweidu = []
      }
    },
    handleCancelInstall() {
      this.indexInstallVisible = false
      this.installIndexObj = {
        judgingAction: null,
        emptyDefaultValue: null,
        trueValue: null,
        trueValueRule: '=',
        falseValue: null,
        falseValueRule: '=',
        judgingConditions: [
          {
            judgmentSymbol: null,
            judgmentValue: null
          }
        ],
        feiguanlianweidu: [],
        name: null,
        indexName: null,
        indexId: null,
        dimensionList: [],
        fieldName: []
      }
    },
    handleInstall() {
      this.indexInstallVisible = false
      this.formulaStrs[this.installIndexObjIndex].installIndexObj = this.installIndexObj
    },
    installIndex(formula, index) {
      var dimensionListTemp = []
      formula.dimensionList.forEach(item => {
        if (item.isDate == 0) {
          dimensionListTemp.push(item)
        }
      })

      this.indexInstallVisible = true
      this.installIndexObjIndex = index

      if (formula.installIndexObj) {
        this.installIndexObj = JSON.parse(JSON.stringify(formula.installIndexObj))
      } else {
        this.installIndexObj = {
          judgingAction: null,
          emptyDefaultValue: null,
          trueValue: null,
          trueValueRule: '=',
          falseValue: null,
          falseValueRule: '=',
          judgingConditions: [
            {
              judgmentSymbol: null,
              judgmentValue: null
            }
          ],
          feiguanlianweidu: [],
          name: formula.name,
          indexName: formula.indexName,
          indexId: formula.indexId,
          aggregateType: formula.aggregateType,
          dimensionList: dimensionListTemp,
          fieldName: []
        }
      }
    },
    indexUnselect(name, index) {
      this.formulaStrs.splice(index, 1, { name: name, indexName: null, indexId: null, dimensionList: [] })
      if (this.formulaStrs) {
        var selecteds = []
        this.formulaStrs.forEach(item => {
          if (this.isValid(item.name)) {
            if (item.dimensionList.length > 0) {
              if (selecteds.length == 0) {
                selecteds = JSON.parse(JSON.stringify(item.dimensionList))
              } else {
                var newSelecteds = []
                selecteds.forEach(item1 => {
                  if (item.dimensionList.find(item2 => item1.dimensionType == item2.dimensionType)) {
                    newSelecteds.push(item1)
                  }
                })
                selecteds = newSelecteds
              }
            }
          }
        })
        this.selectedDimensionList = selecteds
      }
    },
    dragover(event, index) {
      this.selectedFormulaStrIndex = index
    },
    dragstart(event, val) {
      console.log(val)
      this.selectedIndexObj = val
    },
    dragend() {
      if (this.selectedIndexObj && this.selectedFormulaStrIndex != null) {
        if (this.selectedDimensionList == null || this.selectedDimensionList.length == 0) {
          this.selectedDimensionList = this.currentDimensionList
        } else {
          var repeatDimensions = []
          this.selectedDimensionList.forEach(item1 => {
            if (this.currentDimensionList.findIndex(item => item.dimensionType == item1.dimensionType) != -1) {
              repeatDimensions.push(item1)
            }
          })
          if (repeatDimensions.length == 0) {
            this.$message.warning('维度不一致无法添加')
            return
          }
          this.selectedDimensionList = repeatDimensions
        }

        this.formulaStrs.splice(this.selectedFormulaStrIndex, 1, {
          feiguanlianweidu: [],
          name: this.formulaStrs[this.selectedFormulaStrIndex].name,
          indexName: this.selectedIndexObj.name,
          indexId: this.selectedIndexObj.id,
          aggregateType: 'sum',
          dimensionList: this.currentDimensionList
        })
        console.log(this.formulaStrs)
      }
      this.selectedFormulaStrIndex = null
    },
    isOperators(val) {
      if (this.operators.find(item => item == val)) {
        return true
      }
      return false
    },
    // 指标配置项列表初始化获取
    initIndexConfigList() {
      if (this.loading) {
        this.$message.info('刷新太频繁')
        return
      }
      this.indexConfigList = []
      this.loading = true
      getAction(this.url.indexConfigList, {}).then(res => {
        if (res.success) {
          res.result.map(item => {
            item.value = item.id
            item.title = item.configName
            this.indexConfigList.push(item)
          })
          if (this.indexConfigList.length !== 0) {
            // 默认选中第一个配置项
            if (this.currentIndexConfig === undefined) {
              this.currentIndexConfig = this.indexConfigList[0].value
              this.currentIndexConfigChange(this.indexConfigList[0].value, {
                data: {
                  props: this.indexConfigList[0]
                }
              })
            }
          }
        } else {
          this.$message.error(res.message)
        }
      }).finally(() => {
        this.loading = false
      })
    },

    // 刷新指标配置项数据列表
    reLoadIndexConfigList() {
      this.initIndexConfigList()
    },
    // 指标计算函数列表初始化获取
    initCalculateFunctionList() {
      this.calculateFunctionList = []
      getAction(this.url.calculateFunctionList, { pageNo: 1, pageSize: 10000 }).then(res => {
        if (res.success) {
          this.calculateFunctionList = res.result.records
          if (this.calculateFunctionList.length !== 0) {
            // 默认选中第一个配置项
            if (this.currentCalculateFunction === undefined) {
              this.currentCalculateFunction = this.calculateFunctionList[0].id
              this.currentCalculateFunctionChange(this.calculateFunctionList[0].id)
            }
          }
        } else {
          this.$message.error(res.message)
        }
      })
    },

    // 切换指标计算函数事件响应
    currentCalculateFunctionChange() {
      this.formulaStr = this.calculateFunctionList.find(item => item.id == this.currentCalculateFunction).body
      this.formulaStrs = this.analysisFormula(this.formulaStr)
    },
    checkNum(value) {
      return !isNaN(parseFloat(value)) && isFinite(value)
    },
    isValid(str) {
      if (this.checkNum(str)) {
        return false
      }
      return /^\w+$/.test(str)
    },
    isValid2(str) {
      return /^\w+$/.test(str)
    },
    // 分解公式
    analysisFormula(val) {
      var strsTemp = val.split('')
      var strs = []
      var bianliang = ''
      strsTemp.forEach((item, index) => {
        if (this.isValid2(item)) {
          bianliang += item
          if (index == strsTemp.length - 1) {
            strs.push({ name: bianliang, indexName: null, indexId: null, dimensionList: [] })
          }
        } else {
          if (bianliang != '') {
            strs.push({ name: bianliang, indexName: null, indexId: null, dimensionList: [] })
          }
          strs.push({ name: item, indexName: null, indexId: null, dimensionList: [] })
          bianliang = ''
        }
      })
      console.log(strs)
      return strs
    },
    // 切换指标配置事件响应
    currentIndexConfigChange(value, options) {
      console.log('value------------------------------------------------', value)
      console.log('options----------------------------------------------', options)
      this.searchValue = ''
      this.currentIndexList = options.data.props.indexInfoVoList
      this.currentDimensionList = options.data.props.dimensionInfoVoList
      this.selectedIndexOfIdList = []
      this.selectedIndexList = []
      this.form.resetFields()
      this.testCompleteFlag = false
      this.testResult = []
    },
    // 试计算
    test() {
      this.form.validateFields((err, values) => {
        if (!err) {
          var params = this.formatParams(values)

          postAction('/index/compute/scSituationFormula/testRunning', params).then(res => {
            if (res.success) {
              this.testCompleteFlag = true
              this.resultTableColumns = []
              if (res.result != null && res.result.length > 0) {
                for (var key in res.result[0]) {
                  this.resultTableColumns.push({
                    title: key,
                    align: 'center',
                    width: 200,
                    dataIndex: key
                  })
                }
              }
              this.testResult = res.result
            } else {
              this.$message.warning(res.message)
            }
          })
        }
      })
    },
    // 格式化power
    formatPower(val) {
      var formulas = JSON.parse(JSON.stringify(val))
      var formulaTemps = []
      var powers = []
      formulas.forEach((item, index) => {
        if (item.name == '^') {
          var powerObj = {}
          if (formulaTemps[index - 1] != ')') {
            powerObj.value1 = formulaTemps[index - 1]
          } else {
            // 判断括号部分
            var count1 = 0
            var count2 = 0
            // power第一个参数值
            var stringtemp = ''
            // 跳出循环标识
            var xunhhuanFlag = true
            var yiyougongshixiangdaoxu = JSON.parse(JSON.stringify(formulaTemps)).reverse()
            console.log(yiyougongshixiangdaoxu)
            yiyougongshixiangdaoxu.forEach(item1 => {
              if (xunhhuanFlag) {
                if (item1 == ')') {
                  count1++
                }
                stringtemp = item1 + stringtemp
                if (item1 == '(') {
                  count2++
                  if (count1 == count2) {
                    xunhhuanFlag = false
                  }
                }
              }
            })
            powerObj.value1 = stringtemp
          }

          if (formulas[index + 1].name != '(') {
            powerObj.value2 = formulas[index + 1].name
          } else {
            // 判断括号部分
            var bcount1 = 0
            var bcount2 = 0
            // power第一个参数值
            var bstringtemp = ''
            // 跳出循环标识
            var bxunhhuanFlag = true
            for (var i = index + 1; i < formulas.length; i++) {
              if (bxunhhuanFlag) {
                if (formulas[i].name == '(') {
                  bcount1++
                }
                bstringtemp = bstringtemp + formulas[i].name
                if (formulas[i].name == ')') {
                  bcount2++
                  if (bcount1 == bcount2) {
                    bxunhhuanFlag = false
                  }
                }
              }
            }
            powerObj.value2 = bstringtemp
          }

          powers.push(powerObj)
        }
        formulaTemps.push(item.name)
      })
      console.log(powers)
      var formulaTempsStr = ''
      formulaTemps.forEach(item => {
        formulaTempsStr += item
      })
      powers.forEach(item => {
        formulaTempsStr = formulaTempsStr.replace(item.value1 + '^' + item.value2, 'power(' + item.value1 + ',' + item.value2 + ')')
      })
      return formulaTempsStr
    },
    // 组织公式参数
    formatParams(values) {
      var params = JSON.parse(JSON.stringify(this.calculateFunctionList.find(item => item.id == this.currentCalculateFunction)))

      params.body = this.formatPower(this.formulaStrs)

      params.indexName = values.indexName

      params.scale = values.scale

      if (this.checkedDimension == null || this.checkedDimension.length == 0) {
        this.$message.warning('请选择维度')
        return
      }

      var parameters = []
      this.formulaStrs.forEach((item, index) => {
        if (this.isValid(item.name)) {
          if (item.indexName != null && item.indexName != '') {
            var parametersObj = {
              aggregateType: item.installIndexObj == null ? item.aggregateType : item.installIndexObj.aggregateType,
              associatedDimensionIds: this.checkedDimension,
              formulaId: params.id,
              indexId: item.indexId,
              name: item.name
            }
            if (item.installIndexObj) {
              // IFNULL IF操作
              parametersObj.emptyDefaultValue = item.installIndexObj.emptyDefaultValue
              parametersObj.falseValue = item.installIndexObj.falseValueRule == '=' ? item.installIndexObj.falseValue : (item.indexName + item.installIndexObj.falseValueRule + item.installIndexObj.falseValue)
              parametersObj.trueValue = item.installIndexObj.trueValueRule == '=' ? item.installIndexObj.trueValue : (item.indexName + item.installIndexObj.trueValueRule + item.installIndexObj.trueValue)
              parametersObj.judgingAction = item.installIndexObj.judgingAction

              var judgingConditions = []
              item.installIndexObj.judgingConditions.forEach(item1 => {
                if (item1.judgmentSymbol != null && item1.judgmentSymbol != '') {
                  judgingConditions.push({
                    judgmentSymbol: item1.judgmentSymbol,
                    judgmentValue: item1.judgmentValue
                  })
                }
              })

              parametersObj.judgingConditions = judgingConditions

              // judgingConditions
              // judgmentSymbol
              // judgmentValue

              var filters = []
              item.installIndexObj.feiguanlianweidu.forEach(item1 => {
                filters.push({
                  fieldName: item1.tableColumn,
                  fieldValue: item1.value != null && item1.value.length > 0 ? item1.value.join(',') : ''
                })
              })
              parametersObj.filters = filters
            }
            parameters.push(parametersObj)
          } else {
            this.$message.warning('请选择指标')
            return
          }
        }
      })
      params.parameters = parameters
      return params
    },

    // 数据提交处理方法
    // event: 0-数据试计算事件触发逻辑；1-数据保存事件触发逻辑(默认)
    summit(event = 1) {
      var quanbuquanzezhibioa = false
      // 指标选择检查
      if (quanbuquanzezhibioa) {
        this.$message.warning('请选择指标')
        if (event) this.$emit('ok', { complete: 0 }) // 数据保存事件触发逻辑特定(前置)消息回传
        return
      }
      // 试计算完成状态检查
      if (event && !this.testCompleteFlag) {
        this.$message.warning('请点击试计算按钮，完成数据验证')
        if (event) this.$emit('ok', { complete: 0 }) // 数据保存事件触发逻辑特定消息(前置)回传
        return
      }
      // 表单验证检查
      this.form.validateFields((err, values) => {
        if (!err) {
          // 拼装数据结构
          const summitData = JSON.parse(JSON.stringify(this.baseInfo)) // 深拷贝基本信息

          summitData.dataSource = 'situation_data'

          // 拼装指标数据
          const definition = values // 拼装指标定义
          definition.name = definition.indexName
          definition.groupType = definition.isPercent ? undefined : definition.groupType // 根据率值选择设置汇聚方式
          definition.status = 1

          if (definition) {
            definition.tableName = 'USERSQL'
          }

          var dimensions = []

          this.selectedDimensionList.forEach(item => {
            if (this.checkedDimension.findIndex(item1 => item1 == item.id) != -1) {
              var dimension = item
              dimension.tableName = 'USERSQL'
              dimensions.push(dimension)
            }
          })

          // const dimension = this.selectedDimensionList.find(item => item.id == this.checkedDimension) // 获取已选择维度数据

          // if (dimension) {
          //   dimension.tableName = 'USERSQL'
          // }

          const indexData = {
            sit: definition,
            dim: dimensions
          }
          summitData.indexData = indexData

          summitData.situationFormula = this.formatParams(values)

          postAction(this.url.summit, summitData).then(res => {
            if (res.success) {
              this.$message.success('指标增加成功')
              this.$emit('ok', { complete: 1 }) // 数据保存事件触发逻辑特定消息(后置)回传
            } else {
              this.$message.error(res.message)
            }
          }).finally(() => {
            this.$emit('ok', { complete: 0 }) // 数据保存事件触发逻辑特定消息(前置)回传
          })
        } else {
          this.$message.warning('请完成指标定义的输入')
          if (event) this.$emit('ok', { complete: 0 }) // 数据保存事件触发逻辑特定消息(前置)回传
        }
      })
    },

    // 是否率值项选择值变化事件响应
    handleIsPercentChange() {
      this.form.resetFields(['groupType'])
    },

    // 数据提交处理方法
    // event: 0-数据试计算事件触发逻辑；1-数据保存事件触发逻辑(默认)
    // 初始化指标计算函数容器尺寸监听器
    initCalculateFunctionContainerSizeListener() {
      const _this = this
      elementResizeDetector().listenTo(this.$refs.calculateFunctionPanel, () => {
        _this.calculateFunctionContainerHorizontalAlignChange()
      })
    },
    // 指标计算函数容器尺寸变化导致的布局适应事件响应
    calculateFunctionContainerHorizontalAlignChange() {
      if (this.$refs.calculateFunctionPanel.scrollWidth > this.$refs.calculateFunctionPanel.clientWidth) {
        this.calculateFunctionContainerHorizontalAlignIsCenter = false
      } else {
        this.calculateFunctionContainerHorizontalAlignIsCenter = true
      }
    }

  }
}
</script>

<style lang="less" scoped>
::v-deep .ant-checkbox {
  top: 0;
}

::v-deep .ant-checkbox + span {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

::v-deep .ant-form-item {
  margin-bottom: 2px;
}

::v-deep textarea.ant-input {
  margin-bottom: -6.5px !important;
}

.container {
  height: 100%;
  display: flex;
  justify-content: center;
  user-select: none;

  & > .left {
    width: 220px;
    height: 100%;
    background: #fafafa;

    & > .left-title {
      height: 36px;
      line-height: 36px;
      font-size: 15px;
      color: #000022;
      text-align: center;
      background-color: #eff4f9;
    }

    & > .left-operate-box {
      position: relative;
      padding: 10px;
      border-bottom: 4px solid #ffffff;

      & > .ant-select {
        width: calc(100% - 30px);
      }

      & > .ant-input-affix-wrapper {
        width: calc(100% - 30px);
        margin-top: 10px;
      }

      .icon {
        position: absolute;
        width: 20px;
        height: 32px;
        font-size: 20px;
        top: 10px;
        right: 10px;
        cursor: pointer;
        line-height: 35px;
      }
    }

    & > .table-list {
      height: calc(100% - 138px);
      align-items: center;
      justify-content: center;
      overflow-x: hidden;
      overflow-y: auto;

      .table-item {
        cursor: pointer;

        & > p {
          height: 36px;
          line-height: 36px;
          padding: 0 10px;
          margin-bottom: 0;
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
          border-bottom: 1px dashed #e8e8e8;
        }

        &:hover,
        &.active {
          background-color: #eff4f9;
        }
      }
    }
  }

  & > .middle {
    flex: 1;
    height: 100%;
    margin-left: 15px;
    background: #fafafa;
    overflow: hidden;
    position: relative;

    & > .operate-box {
      width: 100%;
      height: 46px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      background: #ffffff;
      border-bottom: 4px solid #ffffff;

      & > .ant-select {
        width: calc(100% - 84px);
      }

      & > .ant-btn {
        margin-right: 0;
      }
    }

    & > .select-box {
      width: 100%;
      height: 236px;
      display: flex;
      align-items: center;
      border-bottom: 4px solid #ffffff;
      overflow-x: auto;
      & > .select-calculate-box {
        display: flex;
        align-items: center;
       .symbol-container {
          width: 40px;
          display: flex;
          justify-content: center;
        }
        .variable-container {
          min-width: 180px;
          height: 100px;
          padding: 0 14px;
          border: 1px solid #cdcdcd;
          border-radius: 4px;
          justify-content: center;
          align-items: center;

          & > ::v-deep .anticon-close {
            position: relative;
            top: 2px;
            right: calc(-100% + 2px);
            cursor: pointer;
          }

          & > .variable-details-container {
            height: calc(100% - 34px);
            display: flex;
            align-items: center;
            flex-direction: column;
            justify-content: space-around;
          }
        }

        & > .variable-container-empty {
          background: #fafafa;
        }

        & > .variable-container-full {
          background: #ffffff;

          &:hover {
            background: #eff4f9;
          }
        }
      }
    }

    & > .result-title {
      height: 36px;
      line-height: 36px;
      font-size: 15px;
      color: #000022;
      text-align: center;
      background-color: #eff4f9;
    }

    & > .result-box {
      width: 100%;
      height: calc(100% - 318px);
      align-items: center;
      justify-content: center;
      overflow-y: auto;
    }
  }

  & > .right {
    width: 220px;
    height: 100%;
    margin-left: 15px;
    background: #fafafa;
    overflow: hidden;
    position: relative;

    & > .right-title {
      height: 36px;
      line-height: 36px;
      font-size: 15px;
      color: #000022;
      text-align: center;
      background-color: #eff4f9;
    }

    & > .right-box-1 {
      height: 40%;
      position: relative;
      padding: 0 10px;
      align-items: center;
      justify-content: center;
      border-bottom: 4px solid #ffffff;
      overflow-y: auto;

      & > ::v-deep .ant-checkbox-wrapper {
        width: 100%;
        line-height: 25px;
        display: flex;
        align-items: center;
      }

      & > ::v-deep .ant-checkbox-wrapper + .ant-checkbox-wrapper {
        margin-left: 0;
      }
    }

    & > .right-box-2 {
      height: calc(60% - 76px);
      position: relative;
      padding: 10px 10px 0 0;
      overflow-y: auto;
    }
  }
}
.install-label {
  line-height: 30px;
}
</style>
